package repositories

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"nodeseller/datamodels"
	mymongo "nodeseller/mongo"
)

type IBill interface {
	//连接数据库
	Conn()(error)
	//插入数据库
	Insert(bill *datamodels.Bill)(error)
	//查询账单
	FindAll(string)([]datamodels.Bill,error)
}

type BillManager struct {
	mongoDataColletion mymongo.Collection
}
func NewBillManager()IBill  {
	mongodb,err := mymongo.Get()
	if err != nil{
		return nil
	}
	return &BillManager{
		mongodb.Collection("bill"),
	}
}
//创建连接
func (p *BillManager)Conn()(error)  {
	if p.mongoDataColletion == nil{
		mongodb,err := mymongo.Get()
		if err != nil{
			return err
		}
		p.mongoDataColletion = mongodb.Collection("bill")
	}
	return nil
}
//创建账单
func (p *BillManager)Insert(bill *datamodels.Bill)(error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  err
	}
	_,err := p.mongoDataColletion.InsertOne(context.TODO(),bill)
	if err != nil{
		return err
	}
	return nil
}
//查询所有账单
func (p *BillManager)FindAll(phonenumber string)(result []datamodels.Bill,err error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return  result,err
	}
	cur,err := p.mongoDataColletion.Find(context.TODO(),bson.M{"phonenumber":phonenumber})
	if err != nil{
		return  result,err
	}
	for cur.Next(context.TODO()){
		var elem datamodels.Bill
		err := cur.Decode(&elem)
		if err != nil{
			return result,err
		}
		result = append(result,elem)
	}
	return result,nil
}
